/**
 * 流程基本设置
 */
import React from 'react';
import { Input, Button, Form, message } from 'antd';

import FlowIcon from '@/components/BizIcon/FlowIcon';
import { savebaseworkflowtemplate } from '@/services/flowManage/templateMange';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import useTreeSelectData from '@/hooks/useTreeSelectData';
import RadioForm from './RadioForm';
import { SelectCategory } from '../../components';

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
    }
};

const btnLayout = {
    wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 4 }
    }
};

const requiredRule = [
    {
        required: true,
        message: '请输入完整的必填项，即可保存'
    }
];

const rules = {
    category: requiredRule,
    companyId: requiredRule,
    templateName: [
        ...requiredRule,
        {
            min: 2,
            max: 50,
            message: '2-50字'
        }
    ],
    scopeGroup: [
        {
            validator(rule, value, callback) {
                if (value.scopeField !== 'company' && value.scopeValue.length === 0) {
                    callback('请输入完整的必填项');
                }
                callback();
            }
        }
    ],
    description: [
        {
            min: 2,
            max: 200,
            message: '只能输入2--200个字符'
        }
    ]
};

const BaseConfig = ({ data = {}, form }) => {
    const {
        templateName,
        category,
        description,
        companyId = '',
        companyName = '',
        scopeField = 'company',
        scopeValue = ''
    } = data;

    const [submitting, setSubmitting] = React.useState(false);
    const [companyTreeData, companyTreeLoading] = useTreeSelectData('company');

    /* 手动收集的字段 */
    const [manualFormFields, setManualFormFields] = React.useState({
        companyId,
        companyName
    });

    const initForm = React.useCallback(() => {
        form.setFieldsValue({
            templateName,
            category,
            companyId,
            companyName,
            description,
            scopeGroup: { scopeField, scopeValue: scopeValue.split(',') }
        });
    }, []);

    const handleSelectCompany = React.useCallback((value, label) => {
        setManualFormFields({ ...manualFormFields, companyId: value, companyName: label[0] });
    }, []);

    React.useEffect(() => {
        initForm();
    }, []);

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, value = {}) => {
            const { scopeGroup = {} } = value;

            const finalFormFields = {
                ...data,
                templateName: value.templateName,
                category: value.category,
                description: value.description,
                scopeField: scopeGroup.scopeField,
                scopeValue: scopeGroup.scopeValue.join(','),
                iconType: 'overtime',
                ...manualFormFields
            };

            if (!err) {
                setSubmitting(true);
                const result = await savebaseworkflowtemplate(finalFormFields);
                if (result && result.code === 10000) {
                    message.success(result.msg);
                } else {
                    message.error(result.msg);
                }
                setSubmitting(false);
            }
        });
    };

    return (
        <Form {...formItemLayout}>
            <Form.Item label="流程名称">
                {form.getFieldDecorator('templateName', { rules: rules.templateName })(<Input />)}
            </Form.Item>
            <Form.Item label="选择分组">
                {form.getFieldDecorator('category', { rules: rules.category })(<SelectCategory />)}
            </Form.Item>
            <Form.Item label="适用公司">
                {form.getFieldDecorator('companyId', { rules: rules.companyId })(
                    <TreeSelectPro
                        loading={companyTreeLoading}
                        showSearch
                        treeDefaultExpandAll
                        treeData={companyTreeData}
                        onChange={handleSelectCompany}
                    />
                    // <SelectCompany onChange={handleSelectCompany} />
                )}
            </Form.Item>
            <Form.Item label="可见范围">
                {form.getFieldDecorator('scopeGroup', { rules: rules.scopeGroup })(
                    <RadioForm companyId={manualFormFields.companyId} />
                )}
            </Form.Item>
            <Form.Item label="流程图标">
                <FlowIcon iconType={data.iconType || 'leave'} />
            </Form.Item>
            <Form.Item label="流程介绍">
                {form.getFieldDecorator('description', { rules: rules.description })(
                    <Input.TextArea rows={4} placeholder="请输入流程简介" />
                )}
            </Form.Item>
            <Form.Item {...btnLayout}>
                <Button type="primary" onClick={handleSubmit} loading={submitting}>
                    提交
                </Button>
            </Form.Item>
        </Form>
    );
};

const withForm = Form.create()(BaseConfig);

export default withForm;
